package com.central.scheduler.master.dispatch.host;

import com.central.scheduler.common.Constants;
import org.apache.commons.collections4.CollectionUtils;
import com.central.scheduler.common.utils.HeartBeat;
import com.central.scheduler.master.dispatch.enums.ExecutorType;
import com.central.scheduler.master.dispatch.executor.context.ExecutionContext;
import com.central.scheduler.master.dispatch.host.assign.HostWorker;
import com.central.scheduler.master.registry.ServerNodeManager;
import com.central.scheduler.remote.utils.Host;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @author Tindy
 * @date 2021/12/21
 * @describe
 * common host manager
 */
public abstract class CommonHostManager implements HostManager {

    /**
     * server node manager
     */
    @Autowired
    protected ServerNodeManager serverNodeManager;

    /**
     * select host
     *
     * @param context context
     * @return host
     */
    @Override
    public Host select(ExecutionContext context) {
        List<HostWorker> candidates = null;
        Long workerGroupId = context.getWorkerGroupId();
        ExecutorType executorType = context.getExecutorType();
        switch (executorType) {
            case WORKER:
                candidates = getWorkerCandidates(workerGroupId);
                break;
            case CLIENT:
                break;
            default:
                throw new IllegalArgumentException("invalid executorType : " + executorType);
        }

        if (CollectionUtils.isEmpty(candidates)) {
            return new Host();
        }
        return select(candidates);
    }

    protected abstract HostWorker select(Collection<HostWorker> nodes);

    protected List<HostWorker> getWorkerCandidates(Long workerGroupId) {
        List<HostWorker> hostWorkers = new ArrayList<>();
        Set<String> nodes = serverNodeManager.getWorkerGroupNodes(workerGroupId);
        if (CollectionUtils.isNotEmpty(nodes)) {
            for (String node : nodes) {
                String heartbeat = serverNodeManager.getWorkerNodeInfo(node);
                int hostWeight = getWorkerHostWeightFromHeartbeat(heartbeat);
                hostWorkers.add(HostWorker.of(node, hostWeight, workerGroupId));
            }
        }
        return hostWorkers;
    }

    protected int getWorkerHostWeightFromHeartbeat(String heartBeatInfo) {
        int hostWeight = Constants.DEFAULT_WORKER_HOST_WEIGHT;
        if (!StringUtils.isEmpty(heartBeatInfo)) {
            HeartBeat heartBeat = HeartBeat.decodeHeartBeat(heartBeatInfo);
            if (heartBeat != null) {
                hostWeight = heartBeat.getWorkerHostWeight();
            }
        }
        return hostWeight;
    }

}
